<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <my-breadcrumb>个人设置</my-breadcrumb>
      </div>
      <el-row>
        <el-col :span="16">
          <!-- 表单标签 -->
          <el-form label-width="80px">
            <el-form-item label="编号">{{userInfo.id}}</el-form-item>
            <el-form-item label="手机号">{{userInfo.mobile}}</el-form-item>
            <el-form-item label="媒体名称">
               <el-input v-model="userInfo.name" />
            </el-form-item>
              <el-form-item label="媒体简介">
              <el-input type="textarea" v-model="userInfo.intro">
              </el-input>
            </el-form-item>
              <el-form-item label="联系邮箱">
             <el-input v-model="userInfo.email" />
            </el-form-item>
              <el-form-item>
            <el-button type="primary" @click="onSubmit" :disabled='isLoading'>保存设置</el-button>
          </el-form-item>
          </el-form>
        </el-col>
       <!-- 上传图片 -->
         <!--
            action 属性是必须要写的
            http-request="hUpload" ：  自定义上传操作
          -->
       <el-col :span="8">
         <el-upload
          class="avatar-uploader"
          :http-request="hUpload"
          action=""
          :show-file-list="false"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
       </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      isLoading: false, // 加载中 loading
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      },
      userInfo: {
        id: '',
        name: '',
        intro: '',
        photo: '',
        email: '',
        mobile: ''
      }
    }
  },
  created () {
    this.loadUserInfo()
  },
  methods: {
    //  获取数据渲染页面
    async loadUserInfo () {
      try {
        const res = await this.$axios({
          method: 'GET',
          url: '/mp/v1_0/user/profile'
        })
        console.log(res)
        //  数据回填
        const { id, name, intro, photo, email, mobile } = res.data.data
        this.userInfo = {
          id, name, intro, email, mobile
        }
        this.imageUrl = photo
      } catch (err) {
        console.log(err)
      }
    },
    // 提交账户信息
    onSubmit () {
      // 验证不通过就不往下执行
      if (!this.validate()) {
        return
      }
      this.doSave()
    },
    // 发送提交修改信息的请求
    async doSave () {
      this.isLoading = true
      const { name, intro, email } = this.userInfo
      try {
        const res = await this.$axios({
          methods: 'PATCH',
          url: '/mp/v1_0/user/profile',
          data: {
            name,
            intro,
            email
          }
        })
        console.log(res)
        // 修改成功
        this.$message.success('修改成功')
        // 去更新layout的名字
        this.$eventBus.$emit('userinfo-update', { newName: name })
        this.isLoading = false
      } catch (err) {
        this.$message.error('修改失败')
        console.log(err)
        this.isLoading = false
      }
    },
    // 自定义表单验证提交信息
    validate () {
      const { name, intro, email } = this.userInfo
      const setEmail = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      if (name === '' || intro === '' || email === '') {
        this.$message.error('用户名, 简介, 邮箱 不能为空')
        return false
      }
      // 验证邮箱格式
      if (!setEmail.test(email)) {
        this.$message.error('邮箱格式不对')
        return false
      }
      return true
    },
    //  验证图片信息
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      // file.size 单位是字节
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 修改用户头像
    // el-upload组件中的 http-request
    // 在弹出框中，点击确认时，它会自动调用
    async hUpload (config) {
      try {
        // 原生的ajax上传文件
        // formData
        // 由于上传的参数是文件，必须要用formData来组装参数
        const fd = new FormData()
        fd.append('photo', config.file)
        const res = await this.$axios({
          method: 'PATCH',
          url: '/mp/v1_0/user/photo',
          data: fd
        })
        console.log(res)
        this.$message('修改头像成功')
        this.imageUrl = res.data.data.photo
        // 去更改layout的图片
        this.$eventBus.$emit('userinfo-update', { newPhoto: this.imageUrl })
      } catch (err) {
        this.$error('修改头像失败')
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #ddd;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
